package Gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSeparator;

import Game.GameClass;
import cardCollections.Hand;
import cards.Card;

/**
 * 
 */

/**
 * @author Charlotte Lewis
 * 
 */
public class mainGui extends JDialog {
	int currentPlayer;
	boolean play;
	JPanel content;
	private JPanel centerPanel;
	private GameClass playGame = new GameClass(5);
	private int playerIndex;
	private Color backgroundColor;
	private Color lightColor;
	private Color darkColor;
	public ArrayList<String> allCards;
	private boolean showAllDealerCards;

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		mainGui window = new mainGui();
		window.setVisible(true);
	}

	public mainGui() throws IOException {
		playGame.deal();
		playerIndex = 4;
		showAllDealerCards = false;
		// theCasino = new casinoRoyale();
		backgroundColor = new Color(61, 112, 112);
		lightColor = backgroundColor.brighter();
		darkColor = backgroundColor.darker();
		allCards = new ArrayList<String>();
		// theCasino.executeClient();

		setUpGui();

		// set up window characteristics
		setContentPane(content);
		setTitle("CAT BlackJack");
		this.setModal(true);
		setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		pack();
	}

	private void setUpGui() {
		content = new JPanel();
		content.setLayout(new BorderLayout());
		content.setBackground(backgroundColor);

		centerPanel = new JPanel();
		centerPanel.setLayout(new BorderLayout());
		centerPanel.setBackground(backgroundColor);

		JPanel southPanel = new JPanel();
		southPanel.setLayout(new GridLayout(1, 4, 3, 3));
		setupSouthPanel(southPanel);

		content.add(southPanel, BorderLayout.SOUTH);

		content.add(centerPanel, BorderLayout.CENTER);

		// display hands
		addAllHandsToGui();
	}

	private void addAllHandsToGui() {
		JLayeredPane dealerLayeredPane = setUpDealerHand();
		JPanel centerNorthPanel = addToCenterOfGridLayout(dealerLayeredPane);
		JPanel dealerPanel = new JPanel();
		dealerPanel.setLayout(new BoxLayout(dealerPanel, BoxLayout.Y_AXIS));
		dealerPanel.add(new JLabel("Dealer:"));
		dealerPanel.add(centerNorthPanel);
		dealerPanel.setBackground(backgroundColor);
		centerPanel.add(dealerPanel, BorderLayout.NORTH);

		JPanel centerEastPanel = new JPanel();
		centerEastPanel.setLayout(new BoxLayout(centerEastPanel,
				BoxLayout.Y_AXIS));
		centerEastPanel.setBackground(backgroundColor);

		JPanel centerWestPanel = new JPanel();
		centerWestPanel.setLayout(new BoxLayout(centerWestPanel,
				BoxLayout.Y_AXIS));
		centerWestPanel.setBackground(backgroundColor);

		// ArrayList<JLayeredPane> hands = new ArrayList<JLayeredPane>();
		int handNumber = 0;
		while (handNumber < playGame.getTotalPlayers()) {

			JLayeredPane player = setUpPlayerHand(handNumber);
			JLabel label = new JLabel("<html><body>Player " + (handNumber + 1)
					+ "<p>Hand value: "
					+ playGame.getHand(handNumber).getHandCount()
					+ "</body></html>");
			JSeparator s = new JSeparator();
			s.setMaximumSize(new Dimension(500, 3));
			// JSeparator s1 = new JSeparator();
			s.setBackground(darkColor);
			// s1.setBackground(Color.DARK_GRAY);
			s.setForeground(lightColor);
			// s1.setForeground(Color.LIGHT_GRAY);
			if (handNumber == this.playerIndex) {
				JPanel centerSouthPanel = addToCenterOfGridLayout(player);

				JPanel playerPanel = new JPanel();
				playerPanel.setLayout(new BoxLayout(playerPanel,
						BoxLayout.Y_AXIS));
				playerPanel.add(label);
				playerPanel.add(centerSouthPanel);
				playerPanel.setBackground(backgroundColor);
				centerPanel.add(playerPanel, BorderLayout.SOUTH);

			} else if (handNumber % 2 == 0) {
				centerWestPanel.add(label);
				centerWestPanel.add(s);
				centerWestPanel.add(player);
				// centerWestPanel.add(s1);
			} else {
				centerEastPanel.add(label);
				centerEastPanel.add(s);
				centerEastPanel.add(player);
				// centerEastPanel.add(s1);

			}
			handNumber++;
		}

		centerPanel.add(centerEastPanel, BorderLayout.EAST);
		centerPanel.add(centerWestPanel, BorderLayout.WEST);
		BufferedImage img = null;
		try {
			img = ImageIO.read(new File("Images\\logo.gif"));
		} catch (IOException e) {

			e.printStackTrace();
		}

		ImageIcon icon = new ImageIcon(img);
		JLabel centerLogo = new JLabel(icon, JLabel.CENTER);

		centerLogo.setBackground(backgroundColor);
		centerPanel.add(centerLogo, BorderLayout.CENTER);

	}

	private JPanel addToCenterOfGridLayout(JLayeredPane paneToAdd) {
		JPanel panel = new JPanel();
		panel.setLayout(new GridBagLayout());
		panel.setBackground(backgroundColor);

		panel.add(paneToAdd);

		return panel;
	}

	private JLayeredPane setUpPlayerHand(int handNumber) {
		Hand h = playGame.getHand(handNumber);

		ArrayList<Card> cards = h.getPlayerHand();
		JLayeredPane layeredPane = displayCards(cards);
		return layeredPane;
	}

	private JLayeredPane setUpDealerHand() {
		Hand dealer = playGame.getDealerHand();
		ArrayList<Card> dealerCards = dealer.getPlayerHand();
		dealerCards.get(0).setFaceUp(this.showAllDealerCards);
		JLayeredPane dealerLayeredPane = displayCards(dealerCards);
		return dealerLayeredPane;
	}

	/**
	 * takes an array list of cards for a hand and displays them in a
	 * JLayeredPane in the order they were found in the list the size of the
	 * JLayeredPane expands to accommodate the size of the cards.
	 * 
	 * @param cards
	 * @return
	 */
	private JLayeredPane displayCards(ArrayList<Card> cards) {
		int xOffset = 20;
		int yOffset = 10;
		JLayeredPane layeredPane = new JLayeredPane();
		int w = cards.size() * xOffset + 60;
		int h = cards.size() * yOffset + 110;
		layeredPane.setPreferredSize(new Dimension(w, h));
		layeredPane.setBackground(backgroundColor);
		layeredPane.setOpaque(true);
		for (int i = 0; i < cards.size(); i++) {
			ImageIcon icon = new ImageIcon(cards.get(i).getcardImage());
			JLabel label = new JLabel(icon, JLabel.CENTER);
			int x = (xOffset * i);
			int y = (yOffset * i);
			int width = 80;
			int height = 120;
			label.setBounds(x, y, width, height);
			layeredPane.add(label, new Integer(i));
		}
		return layeredPane;
	}

	/**
	 * @param eastPanel
	 */
	private void setupSouthPanel(JPanel eastPanel) {
		JButton startGame = new JButton("Start Game");

		startGame.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					playGame();
				} catch (IOException e1) {
					JOptionPane.showMessageDialog(content,
							"Oops! an error occured somewhere...");
				}
			}
		});

		eastPanel.add(startGame);

	}

	public void playGame() throws IOException {
		play = true;
		while (play) {
			try {
				refreshGui();
				JOptionPane.showMessageDialog(content,
						"Welcome to blackjack! \n by C.A.T");

				game: while (!playGame.isEveryoneDone()) {
					for (currentPlayer = 0; currentPlayer < playGame
							.getTotalPlayers(); currentPlayer++) {
						refreshGui();
						if (playGame.getHand(currentPlayer).isStanding()) {
							JOptionPane.showMessageDialog(content, "Player"
									+ (currentPlayer + 1) + " is standing",
									"Hand value: "
											+ playGame.getHand(currentPlayer)
													.getHandCount(),
									JOptionPane.INFORMATION_MESSAGE, null);
						} else if (playGame.getHand(currentPlayer).isBusted()) {
							JOptionPane.showMessageDialog(content, "Player"
									+ (currentPlayer + 1) + " is busted",
									"Hand value: "
											+ playGame.getHand(currentPlayer)
													.getHandCount(),
									JOptionPane.INFORMATION_MESSAGE, null);
						} else { // (!playGame.getHand(i).isStanding()&&!playGame.getHand(currentPlayer).isBusted())

							// JOptionPane.showMessageDialog(content,
							// "\nplayer " + (currentPlayer + 1) + " hand: " +
							// playGame.getHand(i).toString());

							Object[] options = { "hit", "stand", "end game" };
							int n = JOptionPane.showOptionDialog(content,
									"What would player" + (currentPlayer + 1)
											+ " like to do?", "Hand value: "
											+ playGame.getHand(currentPlayer)
													.getHandCount(),
									JOptionPane.YES_NO_CANCEL_OPTION,
									JOptionPane.QUESTION_MESSAGE, null,
									options, options[2]);

							if (n == JOptionPane.YES_OPTION) {
								// JOptionPane.showMessageDialog(content,"player "
								// +(currentPlayer + 1) + " hit" );
								playGame.hit(currentPlayer);
								refreshGui();
							} else if (n == JOptionPane.NO_OPTION) {
								// JOptionPane.showMessageDialog(content,"player "
								// +(currentPlayer + 1) + " stood");
								playGame.stand(currentPlayer);
								refreshGui();
							} else if (n == JOptionPane.CANCEL_OPTION) {
								JOptionPane.showMessageDialog(content,
										"player " + (currentPlayer + 1)
												+ " ended the game");
								// theCasino.closeClient();
								play = false;
								break game;
							} else {
								JOptionPane
										.showMessageDialog(content,
												"fine, we didn't want you to play anyway\nFYI, you stood....");
								playGame.stand(currentPlayer);
								refreshGui();
							}

						}// end of main if
					}// end of for

					playGame.dealer();
					refreshGui();

					// JOptionPane.showMessageDialog(content ,"Dealer hand: " +
					// playGame.getDealerHand().toString() + "\r\n");
				} // end while

				this.showAllDealerCards = true;
				refreshGui();

			} catch (Exception e) {
				JOptionPane.showMessageDialog(content, "Something broke: "
						+ e.getMessage());
			}
			allCards.addAll(playGame.getCardStringToWrite());
			checkIfPlayersWon();
			playGame.newRound();
			playGame.deal();
			this.showAllDealerCards = false;
			setUpGui();
		}
	}

	private void refreshGui() {
		setUpGui();
		setContentPane(content);
		pack();
	}

	private void checkIfPlayersWon() {
		String disp = "";
		for (int i = 0; i < playGame.getTotalPlayers(); i++) {
			if (playGame.checkWin(i) == -1) {
				disp += "Player " + (i + 1) + " won\n";
			} else if (playGame.checkWin(i) == 0) {
				disp += "Player " + (i + 1) + " tied\n";
			} else {
				disp += "Player " + (i + 1) + " lost\n";
			}
		}// end for
		JOptionPane.showMessageDialog(content, disp);
	}

	/*
	 * private void createNonModalDialog(String title, String htmlMessage,
	 * boolean ok){ final JDialog dialog = new JDialog(this, title);
	 * 
	 * //Add contents to it. It must have a close button. JLabel label = new
	 * JLabel("<html><p align=center>" + htmlMessage);
	 * label.setHorizontalAlignment(JLabel.CENTER); Font font = label.getFont();
	 * label.setFont(label.getFont().deriveFont(font.PLAIN, 14.0f));
	 * 
	 * JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new
	 * BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
	 * buttonPanel.add(Box.createHorizontalGlue());
	 * 
	 * if(ok){ //it only needs an ok button
	 * 
	 * JButton ok_btn = new JButton("ok"); ok_btn.addActionListener(new
	 * ActionListener() { public void actionPerformed(ActionEvent e) {
	 * dialog.setVisible(false); dialog.dispose(); } });
	 * 
	 * 
	 * buttonPanel.add(ok_btn); buttonPanel.setBorder(BorderFactory.
	 * createEmptyBorder(0,0,5,5)); } else{ //it needs hit stand and close
	 * JButton close_btn = new JButton("Close"); close_btn.addActionListener(new
	 * ActionListener() { public void actionPerformed(ActionEvent e) {
	 * playGame.stand(currentPlayer); refreshGui(); } });
	 * 
	 * JButton hit_btn = new JButton("Hit"); hit_btn.addActionListener(new
	 * ActionListener() { public void actionPerformed(ActionEvent e) { try {
	 * playGame.hit(currentPlayer); } catch (IOException e1) {
	 * JOptionPane.showMessageDialog(content,"Oops! Something broke!"); }
	 * refreshGui(); } });
	 * 
	 * JButton stand_btn = new JButton("Stand"); stand_btn.addActionListener(new
	 * ActionListener() { public void actionPerformed(ActionEvent e) {
	 * JOptionPane.showMessageDialog(content,"Game over"); play = false; } });
	 * buttonPanel.add(hit_btn); buttonPanel.add(stand_btn);
	 * buttonPanel.add(close_btn); buttonPanel.setBorder(BorderFactory.
	 * createEmptyBorder(0,0,5,5));
	 * 
	 * }
	 * 
	 * 
	 * 
	 * JPanel contentPane = new JPanel(new BorderLayout());
	 * contentPane.add(label, BorderLayout.CENTER); contentPane.add(buttonPanel,
	 * BorderLayout.PAGE_END); contentPane.setOpaque(true);
	 * dialog.setContentPane(contentPane);
	 * 
	 * //Show it. dialog.setSize(new Dimension(300, 150));
	 * dialog.setLocationRelativeTo(this); dialog.setVisible(true);
	 * 
	 * }
	 */

}
